from django.shortcuts import render
from django.views import View
import json
from django import http
from apps.goods.models import SKU
from django_redis import get_redis_connection
import pickle, base64


# Create your views here.

class CartsView(View):
    """购物车管理"""

    def post(self, request):
        """添加购物车数据"""
        # 接受参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 校验参数
        if not all([sku_id, count]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.JsonResponse({'code': 400, 'errmsg': '参数sku_id错误'})
        try:
            # 使用int类型强转count，如果count不是数字，自动会抛出异常
            count = int(count)
        except Exception:
            return http.JsonResponse({'code': 400, 'errmsg': '参数count错误'})
        # 校验selected类型
        if not isinstance(selected, bool):
            return http.JsonResponse({'code': 400, 'errmsg': '参数selected错误'})

        if request.user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            pl.hincrby('carts_%s' % request.user.id, sku_id, count)
            if selected:
                pl.sadd('selected_%s' % request.user.id, sku_id)
            pl.execute()

            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected
            }

            return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_sku': cart_sku})
        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

            if sku_id in cart_dict:
                count += cart_dict[sku_id]['count']

            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()

            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected
            }
            response = http.JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_sku': cart_sku})
            response.set_cookie('carts', cookie_cart_str)
            return response

    def get(self, request):
        """展示购物车数据"""
        if request.user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            cart_dict_list = redis_conn.hgetall('carts_%s' % request.user.id)
            selecteds = redis_conn.smembers('selected_%s' % request.user.id)

            # 将数据转cookie里的数据类型
            sku_ids = cart_dict_list.keys()
            cart_dict = {}
            for sku_id in sku_ids:
                cart_dict[int(sku_id)] = {
                    "count": int(cart_dict_list[sku_id]), # 一定要用int转换，从redis里取出来是byte类型的数据
                    "selected": sku_id in selecteds   # 在里面就是true 不在就是false 这个方法最简单
                }

        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

        # 构造购物车渲染数据
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'selected': cart_dict.get(sku.id).get('selected'),
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * cart_dict.get(sku.id).get('count'),
            })

        return http.JsonResponse({'code': 0,'errmsg': 'ok','cart_skus': cart_skus})

    def put(self, request):
        """修改购物车数据"""
        # 接受参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 校验参数
        if not all([sku_id, count]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.JsonResponse({'code': 400, 'errmsg': '参数sku_id错误'})
        try:
            # 使用int类型强转count，如果count不是数字，自动会抛出异常
            count = int(count)
        except Exception:
            return http.JsonResponse({'code': 400, 'errmsg': '参数count错误'})
        # 校验selected类型
        if not isinstance(selected, bool):
            return http.JsonResponse({'code': 400, 'errmsg': '参数selected错误'})

        if request.user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            pl.hset('carts_%s' % request.user.id, sku_id, count)
            if selected:
                pl.sadd('selected_%s' % request.user.id, sku_id)
            else:
                pl.srem('selected_%s' % request.user.id, sku_id)
            pl.execute()

            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected
            }

            return http.JsonResponse({'code': 0,'errmsg': 'ok','cart_sku': cart_sku})
        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()

            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected
            }
            response = http.JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_sku': cart_sku})
            response.set_cookie('carts', cookie_cart_str)
            return response



    def delete(self, request):
        """删除购物车数据"""
        # 接受参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.JsonResponse({'code': 400, 'errmsg': '参数sku_id错误'})

        if request.user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            pl.hdel('carts_%s' % request.user.id,sku_id)
            pl.srem('selected_%s' % request.user.id,sku_id)
            pl.execute()
            return http.JsonResponse({'code': 0, 'errmsg': 'ok'})
        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

            if sku_id in cart_dict:
                del cart_dict[sku_id]

            cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()

            response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
            response.set_cookie('carts', cookie_cart_str)
            return response


class CartSelectAllView(View):
    """全选购物车"""
    def put(self,request):
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected')

        if selected:
            if not isinstance(selected,bool):
                return http.JsonResponse({'code':0,'errmsg':'参数selected错误'})

        if request.user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            cart_dict_list = redis_conn.hgetall('carts_%s' % request.user.id)
            sku_ids = cart_dict_list.keys()
            if selected:
                redis_conn.sadd('selected_%s' % request.user.id,*sku_ids)
            else:
                redis_conn.srem('selected_%s' % request.user.id,*sku_ids)

            return http.JsonResponse({'code': 0, 'errmsg': 'ok'})

        else:
            cart_str = request.COOKIES.get('carts')
            response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))

                for sku_id in cart_dict.keys():
                    cart_dict[sku_id]['selected'] = selected

                cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
                response.set_cookie('carts', cookie_cart_str)

            return response











